<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\StoreRole;
use App\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RoleController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function index(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : $this->orderBy;
        $orderType = $request->order_type ? $request->order_type : $this->orderType;
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = Role::orderBy($orderBy, $orderType);
        if ($request->get('name')) {
            $lists->where('name', 'like', '%'.$request->get('name').'%');
        }
        return $lists->paginate($pageSize);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * @param StoreRole $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(StoreRole $request)
    {
        Role::create($request->all());
        return response(['message' => '创建成功']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Role  $role
     * @return \Illuminate\Http\Response
     */
    public function show(Role $role)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Role  $role
     * @return \Illuminate\Http\Response
     */
    public function edit(Role $role)
    {
        //
    }

    /**
     * @param StoreRole $request
     * @param Role $role
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function update(StoreRole $request, Role $role)
    {
        $role->update($request->only(['name', 'display_name', 'description']));
        return response(['message' => '修改成功']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Role  $role
     * @return \Illuminate\Http\Response
     */
    public function destroy(Role $role)
    {
        $role->delete();
        return response(['message' => '删除成功']);
    }

    public function permissions(Role $role)
    {
        return $role->permissions->pluck('id');
    }

    public function setPermissions(Request $request, Role $role)
    {
        return $role->syncPermissions($request->permissions);
    }
}
